package com.lmc.form.script;

import com.free.bsf.core.base.Callable;
import com.free.bsf.core.util.ContextUtils;
import com.free.bsf.core.util.HttpClientUtils;
import com.free.bsf.core.util.JsonUtils;
import com.free.bsf.redis.RedisProvider;
import com.qiniu.util.Md5;
import lombok.val;

import java.util.LinkedHashMap;

public class ApiScriptCache extends ApiScript {
    protected  int cacheTime;
    protected ApiScript script;
    public ApiScriptCache(ApiScript script,int cacheTime){
        super(script.scriptInfo,script.form);
        this.script = script;
        this.cacheTime = cacheTime;
    }

    //执行sql
    @Override
    public Object querySql(String sql,Object...ps) {
        return cache(new Object[]{"querySql",sql,ps},()->{
            return script.querySql(sql,ps);
        });
    }
    @Override
    public Object httpPost(String url,Object json){
        return cache(new Object[]{"httpPost",url,json},()->{
            return script.httpPost(url,json);
        });
    }
    @Override
    //http请求 form请求支持
    public Object httpPostForm(String url,Object json) {
        return cache(new Object[]{"httpPostForm",url,json},()->{
            return script.httpPostForm(url,json);
        });
    }
    @Override
    public Object httpGet(String url){
        return cache(new Object[]{"httpGet",url},()->{
            return script.httpGet(url);
        });
    }

    protected Object cache(Object[] key,Callable.Func0 func0){
        RedisProvider redisProvider = ContextUtils.getBean(RedisProvider.class,false);
        if(redisProvider!=null&&cacheTime>0) {
            String cacheKey = Md5.md5(JsonUtils.serialize(key).getBytes());
            return (Object)redisProvider.cache(cacheKey, cacheTime, () -> {
                return func0.invoke();
            }, Object.class);
        }else{
            return func0.invoke();
        }
    }
}
